//
//  AppDelegate.m
//  夺宝吧
//
//  Created by xiaocai on 15/6/15.
//  Copyright (c) 2015年 FangYuan. All rights reserved.
//

#import "AppDelegate.h"
#import <AlipaySDK/AlipaySDK.h>
#import "FirstVC.h"
#import "LastestGoodsVC.h"
#import "ShoppingCarVC.h"
#import "MyDuoBaoVC.h"

#import "MFSideMenuContainerViewController.h"
#import "PayedVC.h"
#import "UMengRgt.h"
#import "WYHelpVC.h"
#import <Bugly/CrashReporter.h>
#import "WYBase64Fun.h"
#import "QiDongVC.h"
#import "APService.h"

#import <IapppayKit/IapppayKit.h>
#import "WXApi.h"
#import "WeiXinManager.h"

#import <TencentOpenAPI/TencentOAuth.h>
#import <TencentOpenAPI/QQApiInterface.h>
#import "QQManager.h"
#import "SinaManager.h"

#import "WYMainTabBarVC.h"
#import "WYDataBase.h"
//#import "NewDuoBaoController.h"
#import "NewDuoBaoVC.h"
#import "SDWebImageManager.h"


@interface AppDelegate ()<WXApiDelegate  ,  WYHelpVCDelegate>

@end

@implementation AppDelegate

#pragma mark - 是否显示购物车
/**
 *  从服务器取出显示 首页图片的 地址 同步方法 不创建线程
 */
- (void)appUiConfig
{
    
    NSString *urlstring = [NSString stringWithFormat:@"%@api/ApiMisc/getAppUiConfig",DBB_IP];
    NSURL *url = [NSURL URLWithString:urlstring];
    NSMutableURLRequest *requet = [NSMutableURLRequest requestWithURL:url];
    [requet setHTTPMethod:@"POST"];
    [requet setValue:[WYRequest httpHeaderFieldString] forHTTPHeaderField:@"User-Agent"];
    NSHTTPURLResponse *response = nil;
    
    NSData *data = [NSURLConnection sendSynchronousRequest:requet returningResponse:&response error:nil];
    if (data) {
        NSDictionary *configu = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
        if (configu) {
            NSDictionary *dict = [configu objectForKey:@"data"];
            if (dict) {
                NSString *show_shopping = [dict objectForKey:@"show_shopping"];
                if (show_shopping) {
                    [[NSUserDefaults standardUserDefaults] setValue:show_shopping forKey:@"show_shopping"];
                    [[NSUserDefaults standardUserDefaults] synchronize];
                }
            }
        }
    }
    
}

/**
 *  启动时候的设置参数
 *
 *  @param application
 *  @param launchOptions
 *
 *  @return
 */
#pragma mark -- 更新后删除数据库文件
- (void)updateClearDatabase{
    
    NSString *buildVersion =   [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleVersion"];
    
    //从userDefault中读取的版本号
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    NSString *oldBuildVersion = [userDefault objectForKey:@"buildVersion"];
    //从CFBundleVersion 中读取的版本号
    NSString *newBuildVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    
    //不相等
    if (![newBuildVersion isEqualToString:oldBuildVersion]){
//        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
       
            NSFileManager *fileManager = [NSFileManager defaultManager];
            NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
            NSString *documentsDirectory = [paths objectAtIndex:0];
            
            NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:NULL];
            NSEnumerator *e = [contents objectEnumerator];
            NSString *filename;
            while ((filename = [e nextObject])) {
                [fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:NULL];
            }
    
        [userDefault setObject:newBuildVersion forKey:@"buildVersion"];

    }
    
    
}


#pragma mark - 启动
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    [self updateClearDatabase];
    self.isLaunch = YES;
    [self appUiConfig];
    
    
    self.window = [[UIWindow alloc]initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    //update by weienjie 20150918
    [[IapppayKit sharedInstance] setAppAlipayScheme:@"iapppay.weixin.com.AiBei.IapppayDbba"];
    
    //end
    
    //微信注册
    [WXApi registerApp:WX_AppID];
    
    //微博注册
    [WeiboSDK registerApp:Sina_AppKey];
    //极光推送
    //update by weienjie 20150917
    // JPush
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        //可以添加自定义categories
        [APService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge |
                                                       UIUserNotificationTypeSound |
                                                       UIUserNotificationTypeAlert)
                                           categories:nil];
    } else {
        //categories 必须为nil
        [APService registerForRemoteNotificationTypes:(UIRemoteNotificationTypeBadge |
                                                       UIRemoteNotificationTypeSound |
                                                       UIRemoteNotificationTypeAlert)
                                           categories:nil];
    }
    [APService setupWithOption:launchOptions];
    //update end
    
    //bug收集注册
    [[CrashReporter sharedInstance] installWithAppId:@"900004685"];
    [[CrashReporter sharedInstance] enableLog:YES];
    //友盟
    [UMengRgt rgtUmengInFo:launchOptions];
    
    [self setUpMainVC];
    
    
//    WYHelpVC *helpVC = [[WYHelpVC alloc] init];
    //首次启动引导图处理
    NSUserDefaults *user2 = [NSUserDefaults standardUserDefaults];
    if (![user2 boolForKey:@"NO_FIRST_FLAG"]) {
        
//        NSFileManager *fileManager = [NSFileManager defaultManager];
//        NSString *path = [WYDataBase getDataBasePath];
//        BOOL isSuccess = [fileManager removeItemAtPath:path error:nil];
        
        WYHelpVC *helpVC = [[WYHelpVC alloc] init];
        helpVC.delegate = self;
//        [navi pushViewController:helpVC animated:NO];
        self.window.rootViewController = helpVC;
        [user2 setBool:YES forKey:@"NO_FIRST_FLAG"];
        [user2 synchronize];
    }else{
        [self setUpRootViewController:YES];
        [self jihuo];
    }
    return YES;
}
#pragma mark - WYHelpVC的代理

-(void)wyHelpHC:(WYHelpVC *)helpVC buttonClick:(UIButton *)sender{
    
//    [self setUpMainVC];
    //已经启动过引导图所以不延时画面
    [self setUpRootViewController:NO];
//    [self jihuo];
}
#pragma mark - 设置主界面
- (void)setUpMainVC{
    /**
     *   主界面的设置 主界面的设置 主界面的设置 主界面的设置 主界面的设置 主界面的设置
     */
    //主界面
    WYMainTabBarVC *homeVC = [WYMainTabBarVC shareMainTaBarVC];
    FirstVC *firstVC = [FirstVC shareFirstVC];
    LastestGoodsVC *lastestGoodsVC = [LastestGoodsVC shareLastestGoodsVC];
    NewDuoBaoVC *myDuoBaoVC = [NewDuoBaoVC shareMyDuoBaoVC];
    
    NSArray *controllers = @[firstVC,lastestGoodsVC,myDuoBaoVC];
//    NSArray *controllers = @[firstVC,lastestGoodsVC,newDuoBaoVC];
    
    
    //是否展示购物车  以及是否显示3个或者4个Tabbar
    NSString *show_shopping = [[NSUserDefaults standardUserDefaults] valueForKey:@"show_shopping"];
    if (show_shopping.integerValue == 1) {
        //显示
        ShoppingCarVC *shoppingCarVC = [ShoppingCarVC shareShoppingCarVC];
        controllers = @[firstVC,lastestGoodsVC,shoppingCarVC,myDuoBaoVC];
//        controllers = @[firstVC,lastestGoodsVC,shoppingCarVC,newDuoBaoVC];
    }
    //firtstVC 是 夺宝吧
    // lastestGoodsVC 是最新揭晓
    // shoppingCarVC 是购物车
    //myDuoBaoVC  是我的夺宝
    
    //TabBar中的controllers
    homeVC.viewControllers = controllers;
    UINavigationController *navi = [[UINavigationController alloc]initWithRootViewController:homeVC];
    navi.navigationBar.hidden = YES;
    
    _leftMenuVC = [[LeftMenuVC alloc]init];
    //分屏控制器
    MFSideMenuContainerViewController *sideMenuVC = [MFSideMenuContainerViewController containerWithCenterViewController:navi leftMenuViewController:_leftMenuVC rightMenuViewController:nil];
    AppDelegate *myDelegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    if(WYMHEIGHT != 568.0){
        myDelegate.autoSizeScaleX = WYMWITH/320.0;
        myDelegate.autoSizeScaleY = WYMHEIGHT/568.0;
    }else{
        myDelegate.autoSizeScaleX = 1.0;
        myDelegate.autoSizeScaleY = 1.0;
    }
    sideMenuVC.leftMenuWidth = 270 * self.autoSizeScaleX;
//    self.window.rootViewController = sideMenuVC;
    self.rtVC = sideMenuVC;
    
    
    [self jihuo];
}

#pragma mark - 设置rootViewController 

- (void)setUpRootViewController:(BOOL)isDelay{
    self.window.rootViewController = self.rtVC;
    //如果上次请求的开关为1 则启动展示图
    NSString *kg = [[NSUserDefaults standardUserDefaults] objectForKey:@"qidong_pic_flag"];
    if ([kg isEqualToString:@"1"]) {
        QiDongVC *qdvc = [[QiDongVC alloc]init];
        self.window.rootViewController = qdvc;
    }
    else{
        if (isDelay){
            if (WYMHEIGHT>480) {
                [NSThread sleepForTimeInterval:1.5];
            }
        }
        
    }
    //调用激活统计接口
}

- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.

}

- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

#pragma mark - 程序进入前台
- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
//    FirstVC *f = [FirstVC shareFirstVC];
//    [f viewWillAppear:YES];
//    
    
//    WYMainTabBarVC *tabVC =  [WYMainTabBarVC shareMainTaBarVC];
//    
//    UIViewController *currentVC = tabVC.selectedViewController;
//    if (![currentVC isKindOfClass:[MyDuoBaoVC class]]){
//        [currentVC setValue:@YES forKey:@"firstFlag"];
//    }
    
    NSInteger maxCacheAge = [SDImageCache sharedImageCache].maxCacheAge;
    NSInteger maxCacheSize = [SDImageCache sharedImageCache].maxCacheSize;
    NSInteger maxCacheCost = [SDImageCache sharedImageCache].maxMemoryCost;
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    NSString *msg1 = [NSString stringWithFormat:@"applicationDidReceiveMemoryWarning:   maxCacheAge:%d maxCacheSize:%d maxCacheCost:%d",maxCacheAge,maxCacheSize,maxCacheCost];
    
    
    NSInteger stactVCCount = [WYMainTabBarVC shareMainTaBarVC].navigationController.viewControllers.count;
    NSString *msg2 = [NSString stringWithFormat:@"applicationDidReceiveMemoryWarning: %d",stactVCCount];
    NSLog(@"%@",msg2);
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    [FirstVC shareFirstVC].isCheckServer = YES;
    [[FirstVC shareFirstVC] viewWillAppear:YES];
    [LastestGoodsVC shareLastestGoodsVC].firstFlag = YES;
    [ShoppingCarVC shareShoppingCarVC].firstFlag = YES;
    
//    [currentVC viewWillAppear:YES];
    
}

- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.

    
}
- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:
}

#pragma mark - 从另外的程序进入另外的程序
//支付宝的处理
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    
    [ShoppingCarVC shareShoppingCarVC].firstFlag = YES;
    //如果极简开发包不可用,会跳转支付宝钱包进行支付,需要将支付宝钱包的支付结果回传给开 发包
    if ([url.host isEqualToString:@"safepay"]) {
        [[AlipaySDK defaultService] processOrderWithPaymentResult:url
                                                  standbyCallback:^(NSDictionary *resultDic) {
                                                      NSLog(@"result = %@",resultDic);
                                                  }]; }
    
    if ([url.host isEqualToString:@"platformapi"]){//支付宝钱包快登授权返回 authCode
        [[AlipaySDK defaultService] processAuthResult:url standbyCallback:^(NSDictionary *resultDic) {
            NSString *rlt = resultDic[@"resultStatus"];
            if ([rlt isEqualToString:@"9000"]) {/*******************支付成功******************/
                if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
                    //跳往支付结果界面刷新结果
                    PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
                    if(self.zfbPay.isChongZhiFlag){
                        payedVC.rltType = ChongZhiSuccess;
                    }else{
                        payedVC.rltType = PdcSuccess;
                    }
                    [payedVC updateViews];
                }
            }else{/*****************支付失败**********************/
                //取消订单
                if (self.zfbPay.isChongZhiFlag) {
                    [self.zfbPay cancelChangzhiOrder];
                }else{
                    [self.zfbPay cancelOrder];
                }

                //跳往支付结果界面
                if ([[WYPublic GetCurrentviewController] class] == [PayedVC class]) {
                    //跳往支付结果界面刷新结果
                    PayedVC *payedVC = (PayedVC *)[WYPublic GetCurrentviewController];
                    if(self.zfbPay.isChongZhiFlag){
                        payedVC.rltType = ChongZhiFailed;
                    }else{
                        payedVC.rltType = PdcFailed;
                    }
                    [payedVC updateViews];
                }
            }
        }];
    }
    else if (YES == [WXApi handleOpenURL:url delegate:self])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    else if (YES == [WeiboSDK handleOpenURL:url delegate:[SinaManager sharedInstance]])
    {
        return [WeiboSDK handleOpenURL:url delegate:[SinaManager sharedInstance]];
    }
#pragma mark - 腾讯第三方登录
    else if (YES == [TencentOAuth HandleOpenURL:url])
    {
        return [TencentOAuth HandleOpenURL:url];
    }
    else if (YES == [QQApiInterface handleOpenURL:url delegate:[QQManager sharedInstance]])
    {
        return [QQApiInterface handleOpenURL:url delegate:[QQManager sharedInstance]];
    }

    else if ([UMSocialSnsService handleOpenURL:url]) {
        return  [UMSocialSnsService handleOpenURL:url];
    }
    else
    {
        //小段注释 专门用于模拟器

        [[IapppayKit sharedInstance] handleOpenUrl:url];
        return YES;
    }
    return YES;
}
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error NS_AVAILABLE_IOS(3_0){
    NSLog(@"--->%@",error);
    
}
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    //设备唯一标识
//    NSLog(@"%@",[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
//                  stringByReplacingOccurrencesOfString: @">" withString: @""]
//                 stringByReplacingOccurrencesOfString: @" " withString: @""]);
    //记录唯一标识
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *registrationID = [APService registrationID];
    [user setObject:registrationID forKey:@"DEVICETOKEN"];
    [user synchronize];

//    [user setObject:[[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
//                     stringByReplacingOccurrencesOfString: @">" withString: @""]
//                     stringByReplacingOccurrencesOfString: @" " withString: @""] forKey:@"DEVICETOKEN"];
    //update by weienjie 20150917
    //注册通知
//    [UMessage registerDeviceToken:deviceToken];
    
    //JPush    
    [APService registerDeviceToken:deviceToken];
    
    //update end
    
}
/************************
 *统计激活
 ************************/
- (void)jihuo
{
    if ([self isDataChanged]) {
        NSString *base64params = [WYBase64Fun base64StringFromText:@"unionId=2|channelId=2"];
        [WYRequest startPostForTongJiWithUrlStR:[NSString stringWithFormat:@"%@%@?param=%@",DBB_YX_IP,JIHUO_URL,base64params] Parameters:nil successBlock:^(NSDictionary *dic) {
            NSNumber *ret = dic[@"ret"];
            if ([ret intValue] == 0) {

                NSString *channelId = [WYPublic getUsefullStr:[dic[@"data"][@"channelId"] stringValue]];
                NSString *unionId = [WYPublic getUsefullStr:[dic[@"data"][@"unionId"] stringValue]];
                NSString *uid = [WYPublic getUsefullStr:[dic[@"data"][@"uid"] stringValue]];

                NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
                
                NSDate *senddate=[NSDate date];
                
                NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
                
                [dateformatter setDateFormat:@"YYYYMMdd"];
                
                NSString *locationString=[dateformatter stringFromDate:senddate];
                [user setObject:locationString forKey:@"Last_data"];
                
                if (channelId.length>0&&unionId.length>0) {
                    [user setObject:channelId forKey:@"TongJi_channelId"];
                    [user setObject:unionId forKey:@"TongJi_unionId"];
                }else if (uid.length>0) {
                    [user setObject:uid forKey:@"TongJi_uid"];
                }
                [user synchronize];
            }
            else
            {
                [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"Last_data"];
                [[NSUserDefaults standardUserDefaults] synchronize];
            }
        } failedBlock:^{
            [[NSUserDefaults standardUserDefaults] setObject:nil forKey:@"Last_data"];
            [[NSUserDefaults standardUserDefaults] synchronize];
            
        } needLog:NO];
    }
}
//获取系统日期
- (BOOL)isDataChanged
{
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    
    NSString *lastData = [user objectForKey:@"Last_data"];

    NSDate *senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"YYYYMMdd"];
    
    NSString *locationString=[dateformatter stringFromDate:senddate];
    
    if (lastData && lastData.length > 0 && [lastData isEqualToString:locationString]) {
        return NO;
    }
    
    [user setObject:locationString forKey:@"Last_data"];

    return YES;
}

//didReceiveRemoteNotification中设置
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
     [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    //update by weienjie 20150917
//    [UMessage didReceiveRemoteNotification:userInfo];
    [APService handleRemoteNotification:userInfo];
    //update end
}

//update by weienjie 20150917
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
     [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    
    // IOS 7 Support Required
    [APService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}
//update end

- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
    if (YES == [WXApi handleOpenURL:url delegate:self])
    {
        return [WXApi handleOpenURL:url delegate:self];
    }
    else if ([UMSocialSnsService handleOpenURL:url]) {
        return  [UMSocialSnsService handleOpenURL:url];
    }
    else
    {
        [[IapppayKit sharedInstance] handleOpenUrl:url];
        return YES;
    }
}

#pragma mark - WXApiDelegate
-(void)onResp:(BaseResp*)resp
{
    NSLog(@"resp:%@",resp);
    if ([resp isKindOfClass:[SendAuthResp class]])
    {
        if (resp.errCode == 0 && ![WeiXinManager wxlogin])//这里的回调会走2次，故➕一个这样的判断
        {
            [WeiXinManager setWxlogin:YES];
            [WeiXinManager getAccess_tokenWithCode:[(SendAuthResp *)resp code]];
        }
    }
    else
    {
        if (resp.errCode == 0)
        {
//            [CustomTools showTipViewWithText:@"分享成功"];
        }
        else if (resp.errCode != -2)
        {
//            [CustomTools showTipViewWithText:@"分享失败"];
        }
    }
}

- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application{
    NSLog(@"application delegate applicationDidReceiveMemoryWarning");
    NSInteger stactVCCount = [WYMainTabBarVC shareMainTaBarVC].navigationController.viewControllers.count;
    
    
    
    //SDWebImage
    NSInteger maxCacheAge = [SDImageCache sharedImageCache].maxCacheAge;
    NSInteger maxCacheSize = [SDImageCache sharedImageCache].maxCacheSize;
    NSInteger maxCacheCost = [SDImageCache sharedImageCache].maxMemoryCost;
    
    [[SDImageCache sharedImageCache] clearDisk];
    [[SDImageCache sharedImageCache] clearMemory];
    [[SDImageCache sharedImageCache] setValue:nil forKey:@"memCache"];
    NSString *msg = [NSString stringWithFormat:@"applicationDidReceiveMemoryWarning: %d  maxCacheAge:%d maxCacheSize:%d maxCacheCost:%d",stactVCCount,maxCacheAge,maxCacheSize,maxCacheCost];
//    UIAlertView *alertView = [[UIAlertView alloc]initWithTitle:@"内寸警告" message:msg delegate:nil cancelButtonTitle:@"确定" otherButtonTitles: nil];
//    [alertView show];
    
    
}
//从storyboard中初始化一个controller
//v 1.1.34
//v 1.1.34 2
//v 1.1.34 3
//v 1.1.34 4
//v 1.1.34
//v 1.1.34 2
//v 1.1.34 3
//v 1.1.34 4
@end

